package com.example.geekweek4;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MethodOneFuture implements Callable<Object> {

    private Integer num;
    public MethodOneFuture(Integer num){
        this.num = num;
    }
    @Override
    public Object call() throws Exception {
        String msg = "";
        try{
            msg = "异步线程"+num;
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            return msg;
        }
    }
    public static void execute() {
        //线程池堵塞队列
        ArrayBlockingQueue<Runnable> workQueue=null;
        //线程池队列
        ThreadPoolExecutor pool=null;

        try {
            //开启线程池
            workQueue=new ArrayBlockingQueue<Runnable>(5);
            pool=new ThreadPoolExecutor(10, 20, 200,
                    TimeUnit.MILLISECONDS, workQueue);
            //创建线程
            Callable rt = new MethodOneFuture(1);
            //执行线程任务并获取返回值
            Future f = pool.submit(rt);
            //将返回的futrue进行类型转换
            String msg = f.get().toString();
            System.out.println(msg);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(pool != null){
                    pool.shutdown();//关闭线程池
                }

            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
    }

    public static void main(String[] args)throws Exception{
        System.out.println("开始执行main。。。。。");
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future future = executorService.submit(new MethodOneFuture(5));
        System.out.println(future.get());

    }
}
